package com.dex4d.ui.dapp.adapter;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.core.CustomApplication;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.dialog.CommonMessageDialog;
import com.dex4d.glide.GlideUtil;
import com.dex4d.ui.dapp.model.History;
import com.dex4d.ui.dapp.model.TabDappEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.functions.Action2;

/**
 * 作者    LiQingyi
 * 时间    2018/12/6 17:06
 * 文件    dex4d-android
 * 描述
 */
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Activity activity;
    private LayoutInflater inflater;
    private List<History> list;

    private int flag;


    /**
     * 构造函数
     *
     * @param activity
     * @param flag     0 浏览记录 1 收藏夹 3 删除完毕
     */
    public HistoryAdapter(Activity activity, int flag) {
        this.flag = flag;
        this.activity = activity;
        this.inflater = LayoutInflater.from(activity);
        this.list = new ArrayList<>();
    }

    public void addAll(List<History> histories) {
        if (histories == null || histories.isEmpty()) {
            return;
        }

        this.list.addAll(histories);
        notifyDataSetChanged();
    }

    /**
     * 确认删除,还需要更新数据库
     */
    public void confirmDelete() {

        int count = 0;

        for (History temp : list) {
            if (temp.isSelected) {
                count += 1;
            }
        }

        if (count == 0) return;

        CommonMessageDialog dialog = new CommonMessageDialog(activity, CommonMessageDialog.DialogStyle.NOTICE);
        dialog.setMsg(String.format(activity.getResources().getString(R.string.dapp_delete_info), count + ""));
        dialog.setLeftBtnTxt(activity.getResources().getString(R.string.cancel));
        dialog.setRightBtnTxt(activity.getResources().getString(R.string.ok));
        dialog.setClickListener(flag -> {
            if (flag) {//取消

            } else {//确认
                Observable.from(list)
                        .filter(history -> {
                            if (history.isSelected) {
                                CustomApplication.getDb().browserDao().updateBookMarkFromId(0, history.id);
                            }
                            return !history.isSelected;
                        })
                        .collect(() -> new ArrayList<>(), (Action2<List<History>, History>) (histories, history) -> {
                            history.isSelected = false;
                            histories.add(history);
                        })
                        .compose(new DefaultTransformer<List<History>>())
                        .subscribe(new ProgressSubscriber<List<History>>(activity, true) {
                            @Override
                            public void onNext(List<History> result) {
                                list.clear();
                                list.addAll(result);
                                notifyDataSetChanged();
                                EventBus.getDefault().post(new TabDappEvent(5));
                            }

                            @Override
                            public void onCompleted() {
                                super.onCompleted();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                            }
                        });
            }
        });

        dialog.show();

    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.dapp_item_history, viewGroup, false);
        return new VH(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

        VH vh = (VH) viewHolder;
        History history = list.get(i);

        vh.title.setText(history.title);
        GlideUtil.displayImg(vh.icon, history.icon);

        if (flag == 0) {//浏览历史
            vh.url.setText(history.getTimestamp());
        } else {//收藏夹
            vh.url.setText(history.url);
        }

        vh.itemView.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("history", history);
            activity.setResult(Activity.RESULT_OK, intent);
            activity.finish();
        });

        vh.bookmark_checked.setVisibility(View.GONE);

    }


    public History getItemData(int position){
        return list.get(position);
    }

    /**
     * 展示删除选择按钮
     */
    public void showDeleteUI(TabDappEvent event) {
        notifyItemRangeChanged(0, getItemCount(), event);
    }

    /**
     * 全选 反选
     *
     * @param event
     */
    public void selectAll(TabDappEvent event) {
        for (History temp : list) {
            if (event.flag == 2) {
                temp.isSelected = false;
            } else if (event.flag == 1) {
                temp.isSelected = true;
            }
        }

        notifyItemRangeChanged(0, getItemCount(), event);
    }

    public void hideDeleteUI(TabDappEvent event) {
        for (History temp : list) {
            temp.isSelected = false;
        }
        notifyItemRangeChanged(0, getItemCount(), event);
    }

    /**
     * 局部更新
     *
     * @param holder
     * @param position
     * @param payloads
     */
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            VH vh = (VH) holder;
            History history = list.get(position);
            TabDappEvent event = (TabDappEvent) payloads.get(0);

            switch (event.flag) {
                case 0:
                case 1:
                case 2:
                    vh.bookmark_checked.setVisibility(View.VISIBLE);
                    if (history.isSelected) {
                        vh.bookmark_checked.setImageResource(R.drawable.dapp_bookmark_selected);
                    } else {
                        vh.bookmark_checked.setImageResource(R.drawable.dapp_bookmark_normal);
                    }
                    break;
                case 3:
                    break;
                case 4:
                    vh.bookmark_checked.setVisibility(View.GONE);
                    break;
                case 5:
                    vh.bookmark_checked.setVisibility(View.GONE);
                    onBindViewHolder(holder,position);
                    break;
                default:
                    break;
            }

            vh.bookmark_checked.setOnClickListener(v -> {
                if (history.isSelected) {
                    history.isSelected = false;
                    vh.bookmark_checked.setImageResource(R.drawable.dapp_bookmark_normal);
                } else {
                    history.isSelected = true;
                    vh.bookmark_checked.setImageResource(R.drawable.dapp_bookmark_selected);
                }
            });

        }
    }

    public void removeItem(int position){
        list.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class VH extends RecyclerView.ViewHolder {
        @BindView(R.id.web_icon)
        ImageView icon;

        @BindView(R.id.web_title)
        TextView title;

        @BindView(R.id.web_url)
        TextView url;

        @BindView(R.id.bookmark_checked)
        ImageView bookmark_checked;

        public VH(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
